import { getById, inc, add,count,remove } from "../../utils/db";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    tag: false,    //false 没有关注；true 已经关注
  },
  async onLoad(e) {
    let id = e.id;    //获取菜谱id

    //获取菜谱详情
    this.getDetail(id)

    //判断是否关注
    this.isLike(id)

  },
  //判断是否关注
  async isLike(id){
    let openid=wx.getStorageSync('openid');
    let result =await count({collection:"likes",openid:openid,menuid:id}).catch(err=>{
      console.error(err)
    })
    // console.log(result)
    if(result.total>0){
      //已经关注
      this.setData({
        tag:true
      })
    }else{
      //没有关注
      this.setData({
        tag:false
      })
    }

  },
  //根据id获取菜谱详情
  async getDetail(id) {

    //实现views累加
    await inc({ collection: "menu", id, field: "views" })
    //查询数据库
    let result = await getById({ collection: "menu", id }).catch(err => {
      console.error(err)
    })
    let detail = result.data;
    //修改导航栏标题
    wx.setNavigationBarTitle({
      title: detail.name
    })

    //渲染到页面
    this.setData({
      detail: detail
    })
  },
  //大屏预览图片
  preview(e) {
    let url = e.currentTarget.dataset.url     //图片链接
    wx.previewImage({
      urls: this.data.detail.image,
      current: url
    })
  },
  //点击进行关注
  async addLike() {
    let menuid = this.data.detail._id;      //菜谱id

    //在likes集合中添加记录
    let result = await add({ collection: "likes", data: { menuid } }).catch(err => {
      console.error(err)
    })
    //menu集合likes字段+1
    await inc({ collection: "menu", id: menuid, field: "likes" }).catch(err => {
      console.log(err)
    })

    //页面的likes字段+1
    this.data.detail.likes++
    this.setData({
      tag: true,
      detail: this.data.detail
    })
  },
  //取消关注
  async cancelLike(){
    let openid=wx.getStorageSync('openid')    //用户openid
    let menuid=this.data.detail._id;      //菜谱id
    let result =await remove({collection:"likes",where:{_openid:openid,menuid:menuid}}).catch(err=>{
      console.log(err)
    })
    // console.log(result)
    //数据库menu中的likes字段数量-1
    await inc({collection:"menu",id:menuid,field:"likes",count:-1})
    this.data.detail.likes--
    //页面likes数量-1
    this.setData({
      detail:this.data.detail,
      tag:false
    })
      

  }

})